<template>
  <div class="order-confirm">
    <van-nav-bar title="填写订单" left-arrow @click-left="onClickLeft">
      <template #left>
        <van-icon name="arrow-left" size="20" color="#1ba784" />
      </template>
    </van-nav-bar>
    <van-cell-group class="contact" inset>
      <van-cell>
        <van-contact-card
          type="edit"
          :tel="contactInfo.contact_phone"
          :name="contactInfo.contact_name"
          @click="onEdit"
        />
      </van-cell>
    </van-cell-group>

    <van-cell-group class="contact" inset>
      <van-cell v-for="(item, index) in list">
        <van-card class="goods-card" :thumb="`${urlHost}${item.product_img}`">
          <template #price>
            <span class="quantity"> {{ item.quantity }}件</span>
          </template>
          <template #title>
            <span class="product-title">{{ item.product_name }}</span>
          </template>
          <template #footer>
            <span class="product-price">
              ￥{{ item.product_price * item.quantity }}
            </span>
          </template>
        </van-card>
      </van-cell>

      <van-cell title="配送" value="助农快递" />
      <van-cell title="收货方式" value="送货上门" />
      <van-cell title="服务" value="免费上门退换" />
    </van-cell-group>
    <van-submit-bar
      :price="totalPrice"
      button-text="提交订单"
      @submit="onSubmit"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showLoadingToast } from 'vant'
import { getOneContact } from '@/api/modules/contact'
import { createOrder } from '@/api/modules/order'
import { useUserStore } from '@/store/user.store'
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const contactInfo = ref({})
const urlHost = import.meta.env.VITE_APP_URL
const list = ref([])

// 总价
const totalPrice = computed(() => {
  return list.value.reduce((total, item) => {
    return total + item.product_price * item.quantity * 100
  }, 0)
})

// 选择联系人
const onEdit = () => {
  router.push('/AddressList')
}

// 提交订单
const onSubmit = async () => {
  await showLoadingToast({
    message: '生成订单中...',
    forbidClick: true
  })
  new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, 2000)
  }).then(async () => {
    // 获取用户id、联系地址id、总价、商品列表
    const { app_user_id: userId } = userStore.userInfo
    const { contact_id: contactId } = contactInfo.value
    const info = {
      userId,
      contactId,
      totalPrice: Math.floor(totalPrice.value / 100).toString(),
      goodsList: list.value.map((item) => {
        return {
          productId: item.product_id,
          quantity: item.quantity
        }
      })
    }
    try {
      const {
        data: { data }
      } = await createOrder(info)
      if (data) {
        showToast('下单成功')
        router.back()
      }
    } catch (error) {
      console.log('error', error)
    }
  })
  // 获取用户id、联系地址id、总价、商品列表
  // const { app_user_id: userId } = userStore.userInfo
  // const { contact_id: contactId } = contactInfo.value
  // const info = {
  //   userId,
  //   contactId,
  //   totalPrice: Math.floor(totalPrice.value / 100).toString(),
  //   goodsList: list.value.map((item) => {
  //     return {
  //       productId: item.product_id,
  //       quantity: item.quantity
  //     }
  //   })
  // }
  // try {
  //   const {
  //     data: { data }
  //   } = await createOrder(info)
  //   if (data) {
  //     showToast('下单成功')
  //     router.back()
  //   }
  // } catch (error) {
  //   console.log('error', error)
  // }
}

// 获取默认联系人信息
// 从购物车页面上来的话必定是默认联系人
// 如果是从地址列表页面过来的话则是选择的联系人
const getDefContact = async () => {
  const { app_user_id: user_id } = userStore.userInfo
  const { curContactId } = userStore
  // 如果设置了当前联系人id的话则获取当前联系人信息
  if (curContactId !== '') {
    const {
      data: { data }
    } = await getOneContact({ contact_id: curContactId })
    if (data) {
      contactInfo.value = data
    }
    return
  } else {
    // 如果灭有获取到当前联系人id则获取默认联系人信息
    const {
      data: { data }
    } = await getOneContact({ user_id })
    if (data) {
      contactInfo.value = data
    }
  }
}

// 返回上一页
const onClickLeft = () => {
  router.go(-1)
}
onMounted(() => {
  console.log(route.query)
  if (route.query.oneGoods) {
    console.log('oneGoods', JSON.parse(route.query.oneGoods))
    const oneGoods = JSON.parse(route.query.oneGoods)
    oneGoods.quantity = 1
    list.value = [oneGoods]
  } else {
    list.value = JSON.parse(route.query.list)
  }

  console.log(router.options.history.state.back)
  getDefContact()
})
</script>

<style lang="less" scoped>
.contact {
  margin-top: 16px;
}
.order-confirm {
  background-color: #f5f5f5;
  min-height: 100vh;
}
.goods-card {
  margin: 0;
  background-color: #fff;
}

.product-price {
  color: #ff3800;
  font-size: 20px;
  padding-left: 10px;
}
.quantity {
  font-size: 20px;
}
.product-title {
  font-size: 16px;
}
</style>
